<?php
/**
 * Gerenciando logs
 */
class Log {
    public static $instance = null;
    public static $filename = null;
    public $handle = null;
    public $lines = '';

    private function __construct(){
        if ( is_null(self::$filename) ){
          self::$filename =  'log-' . date('Ymd_His') . '.txt';
        }
        $this->handle = fopen(self::$filename, 'wb' );
        if ($this->handle === false){
            throw new Exception('Não foi possível abrir o arquivo.', E_CORE_ERROR);
        }
    }

    private function __destroy(){
      unset(self::$instance);
      unset($this->handle);
      unset($this->lines);
    }

    public static function setFilename($filename){
      self::$filename = $filename;
    }

    /**
     * Pega uma instancia de Log
     * @return Log
     */
    public static function getInstance(){
        return (is_null(self::$instance) ? self::$instance = new self() : self::$instance);
    }

    public static function Add($text,$lineBreak = false) {
        $log = self::getinstance();
        if ($lineBreak) {
          $text .= "\n";
        }
        $log->lines .= $text;
        fwrite($log->handle, date('d/m/Y H:i:s - '). $text);
    }

    public static function getLines(){
        $log = self::getinstance();
        return $log->lines;
    }
}